package org.jks.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jks.controller.ConfigController;
import org.jks.model.Category;


public class Config {
	public static String TITLE = "FSW";
	public static List<NavigationItem> NAVIGATIONS = new ArrayList<NavigationItem>();
	public static int HOME_INDEX = 1;
	public static int SEARCH_INDEX = 2;
	public static int ABOUT_US_INDEX = 3;

	public static void initNavigations() {
		NAVIGATIONS.clear();
		NavigationItem item1 = new NavigationItem();
		item1.setLabel("首页");
		item1.setSrc("/");
		item1.setCategoryId(-1);
		NAVIGATIONS.add(item1);

		int index = 2;
		List<Category> categories = ConfigController.getCategories();
		if(categories != null){
			for(Category category: categories){
				NavigationItem item = new NavigationItem();
				item.setCategoryId(category.getId());
				item.setLabel(category.getName());
				item.setSrc("/article/"+ (index++) + "/"+category.getId());
				NAVIGATIONS.add(item);
			}
		}
		
		NavigationItem itemSearch = new NavigationItem();
		itemSearch.setLabel("搜索");
		itemSearch.setSrc("/search");
		itemSearch.setCategoryId(-1);
		NAVIGATIONS.add(itemSearch);
		SEARCH_INDEX = NAVIGATIONS.size();
		NavigationItem itemAbout = new NavigationItem();
		itemAbout.setLabel("关于我们");
		itemAbout.setSrc("/about");
		itemAbout.setCategoryId(-1);
		NAVIGATIONS.add(itemAbout);
		ABOUT_US_INDEX = NAVIGATIONS.size();
	}
	
	public static int getSelectIndexByCategoryId(long categoryId){
		if(!NAVIGATIONS.isEmpty()){
			int index = 1;
			for(NavigationItem item : NAVIGATIONS){
				if(item.getCategoryId() == categoryId){
					return index;
				}
				index++;
			}
		}
		return 0;
	}

	public static void init(HttpServletRequest request, HttpServletResponse response, HttpSession session,
			Map<String, Object> map, int select_index) {
		response.setCharacterEncoding("UTF-8");
		
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		
		initNavigations();
		if(session.getAttribute("username") != null){
			map.put("username", session.getAttribute("username"));
		}
		map.put("basepath", basePath);
		map.put("title", Config.TITLE);
		map.put("current", select_index);
		map.put("navigations", Config.NAVIGATIONS);
	}
}
